<template>
  <div class="app-container">
    <el-form :model="queryParam" ref="queryForm" :inline="true">
      <el-form-item label="手机号：">
        <el-input v-model="queryParam.userName" clearable></el-input>
      </el-form-item>
      <el-form-item label="真实姓名：">
        <el-input v-model="queryParam.realName" clearable></el-input>
      </el-form-item>
      <el-form-item label="职位：">
        <el-input v-model="queryParam.jobTitle" clearable></el-input>
      </el-form-item>
      <el-form-item label="人员类别：">
        <tree-select v-model="queryParam.departmentIdList" :data="departmentTree" :clearable="true"
          placeholder="人员类别" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm" v-has-perm="['user:employee:page']">查询</el-button>
        <el-button @click="clearForm">重置</el-button>
        <el-button @click="clearPass(ids)" type="success" v-has-perm="['user:employee:resetPwd']">重置密码</el-button>
        <el-popover placement="bottom" trigger="click" :width="240">
          <template #reference>
            <el-button type="primary" class="link-left" v-has-perm="['user:employee:import']">导入
            </el-button>
          </template>
          <div class="wdd-popover-content">
            <a target="_blank"
              href="https://tongzhou-exam.oss-cn-beijing.aliyuncs.com/template/web-file/template/file/%E5%91%98%E5%B7%A5%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
              style="float: left; margin-left: 5px">
              <el-button type="success">Excel 模板</el-button>
            </a>
            <el-upload style="float: left; margin-left: 5px" accept=".xlsx" action="/api/user/v1/employee/import"
              :show-file-list="false" :on-progress="uploadProgress" :on-success="uploadExcelSuccess"
              :on-error="uploadError">
              <el-button type="success" class="link-left">Excel 导入</el-button>
            </el-upload>
          </div>
        </el-popover>
        <el-button type="primary" class="link-left" @click="userExport" v-has-perm="['user:employee:export']">导出
        </el-button>
        <router-link :to="{ path: '/user/employee/edit' }" class="link-left">
          <el-button type="primary" v-has-perm="['user:employee:create']">添加</el-button>
        </router-link>
        <el-button type="danger" @click="doDeleteButton(ids)">批量删除</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" border fit highlight-current-row style="width: 100%"
      @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column width="60px" align="center">
        <template #default="{ row }">
          <el-avatar :size="35" :src="row.imagePath" class="user-image-avatar"></el-avatar>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="id" label="Id" width="90px" /> -->
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="realName" label="真实姓名" />
      <el-table-column prop="departmentLevel" label="人员类别" />
      <el-table-column prop="jobTitle" label="职位" />
      <!-- <el-table-column prop="workNo" label="工号" /> -->
      <el-table-column prop="idCard" label="身份证号" />
      <el-table-column prop="statusStr" label="状态" />
      <el-table-column width="280px" label="操作" style="display:flex">
        <template #default="{ row }">
          <router-link :to="{ path: '/user/employee/train', query: { userId: row.id } }" class="lin-left">
            <el-button  size="small" class="wdd-button-mini" type="success">培训
            </el-button>
          </router-link>
          <router-link :to="{ path: '/user/employee/badRule', query: { userId: row.id } }" class="lin-left">
            <el-button  size="small" class="wdd-button-mini" type="primary">违规
            </el-button>
          </router-link>
          <router-link :to="{ path: '/user/employee/rp', query: { userId: row.id } }" class="lin-left">
            <el-button size="small" class="wdd-button-mini" type="primary" plain>奖惩
            </el-button>
          </router-link>
          <router-link :to="{ path: '/user/employee/improve', query: { userId: row.id } }" class="lin-left">
            <el-button size="small" class="wdd-button-mini" type="warning">技能
            </el-button>
          </router-link>
          <router-link :to="{ path: '/user/employee/experience', query: { userId: row.id } }" class="lin-left">
            <el-button size="small" class="wdd-button-mini" type="success" plain>经历
            </el-button>
          </router-link>
          <router-link :to="{ path: '/user/employee/edit', query: { id: row.id } }" class="lin-left">
            <el-button v-has-perm="['user:employee:update']" size="small" class="wdd-button-mini">编辑
            </el-button>
          </router-link>
          <el-button style=" margin-top: 10px;"  type="danger" @click="userDelete(row)" size="small"  class="wdd-button-mini lin-left"
            v-has-perm="['user:employee:delete']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" v-model:page="queryParam.pageIndex"
      v-model:limit="queryParam.pageSize" @pagination="search" />
  </div>
</template>

<script>
import { employeePage, employeeDelete, employeeExport, deleteUser, resetPassword } from '@/api/user';
import { tree } from '@/api/department';

export default {
  name: 'EmployeeList',
  data() {
    return {
      VITE_APP_RESOURCE_URL: import.meta.env.VITE_APP_RESOURCE_URL,
      queryParam: {
        userName: null,
        realName: null,
        jobTitle: null,
        pageIndex: 1,
        pageSize: 10,
        departmentIdList: []
      },
      tableData: [],
      departmentTree: [],
      total: 0,
      canLoad: true,
      ids: []
    };
  },
  mounted() {
    this.init();
    this.canLoad = false;
  },
  activated() {
    this.init();
  },
  deactivated() {
    this.canLoad = true;
  },
  methods: {
    init() {
      if (!this.canLoad) {
        return;
      }
      tree().then(re => {
        this.departmentTree = re.response;
      });
      this.search();
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      console.log(this.ids)
    },
    //批量删除
    doDeleteButton(rows) {
      if (rows.length !== 0) {
        this.$confirm('是否确认删除这' + rows.length + '条数据?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          console.log(rows, 'rows')
          return deleteUser(rows)
        }).then(() => {
          this.search();
          this.$message.success("删除成功");
        })
      } else {
        this.$message.error("未选择数据");
      }
    },
    search() {
      employeePage(this.queryParam).then(data => {
        const re = data.response;
        this.tableData = re.list;
        this.total = re.total;
        this.queryParam.pageIndex = re.pageNum;
      });
    },
    userDelete(row) {
      this.$confirm('此操作将永久删除该员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        employeeDelete(row.id).then(re => {
          if (re.code === 1) {
            this.search();
            this.$message.success(re.message);
          } else {
            this.$message.error(re.message);
          }
        });
      });
    },
    submitForm() {
      this.queryParam.pageIndex = 1;
      this.search();
    },
    clearForm() {
      this.queryParam = {
        userName: null,
        realName: null,
        departmentIdList: [],
        pageIndex: 1,
        pageSize: 10
      };
      this.search();
    },
    //重置密码
    clearPass(ids) {
      console.log(ids)
      this.$confirm('此操作将重置密码, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        resetPassword(ids).then(res => {
          if (res.code === 1) {
            this.$message({
              message: '重置成功，新密码为：' + res.response ,
              center: true,
              type: 'success'
            });
          } else {
            this.$message.error(res.message);
          }
        })
      });

    },
    userExport() {
      employeeExport(this.queryParam).then(data => {
        if (data.code === 1) {
          window.open(data.response, '_blank');
        } else {
          this.$message.error(data.message);
        }
      });
    },
    uploadProgress() {
      this.loading = this.$loading({
        lock: true,
        text: '文件上传中…',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.5)'
      });
    },
    uploadExcelSuccess(re, file) {
      this.loading.close();
      if (re.code === 1) {
        this.search();
        window.location.href = re.response;
      } else {
        this.$message.error(re.message);
      }
    },
    uploadError() {
      this.loading.close();
      this.$message.error('文件上传失败，请检查文件大小或文件格式');
    }
  }
};
</script>
<style>
.lin-left{
  margin: 0 0 10px 5px;
}
</style>